<?php
header('Content-Type: application/json');

$seat = $_GET['seat'];
$data = get_client_data($seat);
$controllers = get_client_info($data);

echo json_encode($controllers, JSON_UNESCAPED_UNICODE);

function get_client_data($seat) {
  if ($seat == '其他') {
    return '';
  }

  // 定义Cookie存储路径
  $cookie_jar = dirname(__FILE__) . "/seat_atcos_cookie.txt";

  // 将cookie存入文件
  // $url = "http://172.22.107.22/atcos/loginGet?userName={$seat}&pwd={$seat}";
  $url = "http://172.22.107.22/atcos/loginGet?userName=PREP&pwd=PREP";
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  // curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_HEADER, false);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar);
  $content = curl_exec($ch);
  curl_close($ch);

  // 到指定页面获取数据
  $ch = curl_init();
  $url = "http://172.22.107.22/atcos/workingHours/getAllNotEndWorkingHours?seatCode={$seat}";
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HEADER, false);
  // curl_setopt($ch, CURLOPT_HEADER, 0);
  // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar);
  $html = curl_exec($ch);
  // var_dump($html);
  curl_close($ch);
  return $html;
}

function get_client_info($html) {

  $result = array(
    'count' => 0,
    'conA' => '',
    'conB' => '',
    'conC' => '',
    'conAS' => '',
    'conBS' => '',
    'conCS' => '',
    'list' => [],
  );
  if ($html == '') {
    return $result;
  }

  $res = json_decode($html, true);

  foreach ($res as $user) {
    $userInfo = array(
      'userId' => $user['userId'],
      'userName' => $user['userName'],
      'seatPost' => $user['seatPost']['name'],
      'seatRole' => $user['seatRole']['name'],
    );
    array_push($result['list'], $userInfo);
    if ($user['seatRole']['name'] == '管制' || $user['seatRole']['name'] == '教员') {
      if ($user['seatPost']['name'] == '管制岗') {
        $result['conA'] = $userInfo;
        $result['count']++;
      } elseif ($user['seatPost']['name'] == '协调岗') {
        $result['conB'] = $userInfo;
        $result['count']++;
      } elseif ($user['seatPost']['name'] == '第三岗') {
        $result['conC'] = $userInfo;
        $result['count']++;
      }
    } else {
      if ($user['seatPost']['name'] == '管制岗') {
        $result['conAS'] = $userInfo;
        $result['count']++;
      } elseif ($user['seatPost']['name'] == '协调岗') {
        $result['conBS'] = $userInfo;
        $result['count']++;
      } elseif ($user['seatPost']['name'] == '第三岗') {
        $result['conCS'] = $userInfo;
        $result['count']++;
      }
    }
  }
  return $result;
}